package com.starblink.android.common.route

import android.content.Context
import android.net.Uri
import androidx.core.net.toUri
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.service.PathReplaceService
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.urllink.UriLinkConfig
import com.starblink.android.basic.urllink.UriLinkConfig.isHttpLink
import com.starblink.android.basic.urllink.UriLinkConfig.isSchemaGUANG
import com.starblink.basic.ext.nowTime
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import java.lang.Exception
import java.net.URLEncoder

@Route(path = "/common/path_replace")
class SkPathReplaceServiceImpl : PathReplaceService {
    override fun init(context: Context?) {

    }

    override fun forString(srcPath: String?): String? {
        val now = nowTime()
        SKLogger.i(TAG, "forString, begin: $srcPath")
        var resPath = srcPath
        if (resPath?.isHttpLink() == true) {
            return srcPath
        }
        // not here handle http/https links
        resPath = preDoPath(resPath)
        SKLogger.i(TAG, "forString, end: $resPath , spent time: ${nowTime() - now}ms")
        return resPath
    }

    override fun forUri(uri: Uri?): Uri? {
        val now = nowTime()
        SKLogger.i(TAG, "forUri, begin: $uri")
        if (uri.toString().isHttpLink()) {
            return uri
        }

        var resUri = if (uri != null) {
            var uriStr = uri.toString()
            if (uriStr.isSchemaGUANG()) {
                uriStr = uriStr.replace(UriLinkConfig.SCHEME_GUANG, "")
            }
            if (uriStr.startsWith(PATH_SEPARATOR, false).not()) {
                uriStr = PATH_SEPARATOR + uriStr
            }
            Uri.parse(UriLinkConfig.SCHEME_GUANG + uriStr)
        } else {
            null
        }
        if (resUri != null) {
            val path = resUri.path
            if (resUri.scheme.isNullOrEmpty() || resUri.toString().isSchemaGUANG()) {
                try {
                    val nPath = preDoPath(path, resUri)
                    resUri = if (nPath?.isNotEmpty() == true) {
                        Uri.parse(nPath.let {
                            if (resUri!!.encodedQuery.isNullOrEmpty()) {
                                "${UriLinkConfig.SCHEME_GUANG}$it"
                            } else {
                                "${UriLinkConfig.SCHEME_GUANG}$it?${resUri!!.encodedQuery}"
                            }
                        })
                    } else {
                        resUri
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }

        SKLogger.i(TAG, "forUri, end: $resUri, spent time: ${nowTime() - now}ms")
        return resUri
    }

    private fun preDoPath(srcPath: String?, uri: Uri? = null): String? {
        var resPath = srcPath
        if (resPath?.isNotEmpty() == true) {
            if (resPath.isSchemaGUANG()) {
                resPath = resPath.replace(UriLinkConfig.SCHEME_GUANG, "")
            }
            // not start with "/"
            if (resPath.startsWith(PATH_SEPARATOR, false).not()) {
                resPath = PATH_SEPARATOR + resPath
            }
            val group = try {
                resPath.substring(1, resPath.indexOf(PATH_SEPARATOR, 1))
            } catch (e: StringIndexOutOfBoundsException) {
                ""
            }
            if (group.isEmpty()) {
                resPath = RoutePage.getRealRouteStrFlutterTransNative(resPath, uri)
            }
        }
        return resPath
    }


    companion object {

        const val TAG = "SkPathReplaceServiceImpl"

        const val PATH_SEPARATOR = '/'

    }

}